import java.util.*;

class Solution {
    private Set<List<Integer>> set;
    private List<Integer> path;
    private List<List<Integer>> ret;
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        set = new HashSet<>();
        path = new ArrayList<>();
        ret = new ArrayList<>();
        dfs(0, candidates, target);
        Iterator<List<Integer>> it = set.iterator();
        while(it.hasNext()) {
            ret.add(it.next());
        }
        return ret;
    }

    private void dfs(int sum, int[] candidates, int target) {
        if(sum == target){
            set.add(new ArrayList<>(path));
            return;
        }
        if(sum > target) {
            return;
        }
        for(int i = 0; i < candidates.length; i++) {
            path.add(candidates[i]);
            sum += candidates[i];
            dfs(sum, candidates, target);
            path.remove(path.size()-1);
            sum -= candidates[i];
        }
    }
}